using System.Reflection.PortableExecutable;
using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.StandardParts.Commands;

/// <summary>
/// 设备点检标件更新命令。
/// </summary>
public sealed record UpdateStandardPartsCommand(long Id, EquipInspectionStandardPartsDto StandardParts) : IRequest<IResult<bool>>;

internal sealed class UpdateStandardPartsCommandHandler(IRepository<EquipInspectionStandardParts> repo) : IRequestHandler<UpdateStandardPartsCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateStandardPartsCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.StandardPartNo == request.StandardParts.StandardPartNo && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("标准件编号已存在");
        }

        var standardParts = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (standardParts == null)
        {
            return Result.Failure("未找到要更新的标准件");
        }

        standardParts.StandardPartNo = request.StandardParts.StandardPartNo;
        standardParts.StandardPartName = request.StandardParts.StandardPartName;
        standardParts.LineId = request.StandardParts.LineId;
        standardParts.WorkstationIds = request.StandardParts.WorkstationIds;
        standardParts.Remark = request.StandardParts.Remark;
        standardParts.Status = request.StandardParts.Status;

        var ok = await repo.UpdateAsync(standardParts, m => new
        {
            m.StandardPartNo,
            m.StandardPartName,
            m.LineId,
            m.WorkstationIds,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
